<script>
import {loginApi} from '@/api/index.js'
import {setToken} from '@/utils/auth.js'
export default {
    data() {
        return {
            mobile: '13911111111', // 手机号
            // mobile: '13912345678', // 手机号
            code: '246810', // 验证码
            rules: {
                mobile: [
                    { required: true, message: '请填写手机号', trigger: 'onBlur' },
                    {
                        pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                        message: '请输入正确的手机号',
                        trigger: 'onBlur'
                    }
                ],
                code: [
                    { required: true, message: "请填写验证码", trigger: "onBlur" },
                    { pattern: /^\d{6}$/, message: "验证码长度为6", trigger: "onBlur" },
                ]
            },
            loading: false
        }
    },
    methods: {
        async onSubmit(data) {
            this.loading = true
            // axios请求返回的是Promise对象
            try {
                const res = await loginApi(data)
                // setToken(res.data.data)
                this.$store.commit('setToken', res.data.data)
                this.$toast.success('登录成功')
                // 登录成功，跳转我的页面
                const url = this.$route.query.url
                if (url) {
                  this.$router.push(url)
                } else {
                  this.$router.push('/layout/home')
                }
            } catch{
                this.$toast.fail('登录失败')
            } finally {
                this.loading = false
            }
                
        }
    }
};
</script>

<template>
  <div class="login">
    <!-- 导航栏 -->
    <van-nav-bar title="登录" />
    <!-- 表单区域 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        type="text"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit" :loading="loading" loading-text="加载中..."
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>



<style lang="less">
.login {
}
</style>